package com.edee.bigday.commodity.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edee.bigday.commodity.dao.SpuInfoDao;
import com.edee.bigday.commodity.entity.*;
import com.edee.bigday.commodity.feign.CouponFeignService;
import com.edee.bigday.commodity.feign.SearchFeignService;
import com.edee.bigday.commodity.feign.WareFeignService;
import com.edee.bigday.commodity.service.*;
import com.edee.bigday.commodity.vo.*;
import com.edee.common.constant.CommodityConstant;
import com.edee.common.to.SkuHasStockVo;
import com.edee.common.to.SkuReductionTo;
import com.edee.common.to.SpuBoundTo;
import com.edee.common.to.es.SkuEsModel;
import com.edee.common.utils.PageUtils;
import com.edee.common.utils.Query;
import com.edee.common.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 该保存逻辑适合使用@GlobalTransactional（Seata的AT 分布式事务）
     * @param vo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1、保存spu基本信息(cms_spu_info)：
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        //2、保存spu的描述图片(cms_spu_info_desc)：
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(spuInfoEntity.getId());
        descEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(descEntity);

        //3、保存spu的图片集(cms_spu_images)：
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        //4、保存spu的规格参数(cms_product_attr_value)：
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(attr.getAttrId());
            productAttrValueEntity.setAttrName(attrService.getById(attr.getAttrId()).getAttrName());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
//        productAttrValueService.saveBatch(collect);
        productAttrValueService.saveProductAttr(collect);

        //5、保存spu的积分信息(bigday_sms.sms_spu_bounds)：
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        //将页面提交的积分bounds交给数据传输对象spuBoundTo：
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败！");
        }

        //6、保存当前spu对应的所有sku信息：
        //6.1、sku的基本信息(cms_sku_info)：
        List<Skus> skus = vo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {
                String defaultImage = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImage = image.getImgUrl();
                    }
                }
                //  private String skuName;
                //  private BigDecimal price;
                //  private String skuTitle;
                //  private String skuSubtitle;
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                //设置默认图片：
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                //保存sku基本信息：
                skuInfoService.saveSkuInfo(skuInfoEntity);

                //6.2、设置sku的图片信息(cms_sku_images)：
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> skuImages = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    //返回true就是要保留的，false是要剔除的。
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                //保存sku图片：
                skuImagesService.saveBatch(skuImages);
                //6.3、设置sku的销售属性信息(cms_sku_sale_attr_value)：
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(att -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(att, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                //保存sku销售属性：
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                //6.4、sku的优惠、满减等信息(bigday_sms.sms_sku_ladder、sms_sku_full_reduction、sms_member_price)：
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                //因为item中没有skuId，所以，还要单独设置：
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败！");
                    }
                }
            });
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity infoEntity) {
        this.baseMapper.insert(infoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and(wrapper->{
                wrapper.eq("id",key).or().like("spu_name",key);
            });
        }
        String status = (String)params.get("status");
        if(!StringUtils.isEmpty(status)){
            queryWrapper.eq("publish_status",status);
        }
        String brandId = (String)params.get("brandId");
        if(!StringUtils.isEmpty(brandId)&&!"0".equalsIgnoreCase(brandId)){
            //增加对brandId为0时的判断
            queryWrapper.eq("brand_id",brandId);
        }
        String catalogId = (String)params.get("catalogId");
        if(!StringUtils.isEmpty(catalogId)&&!"0".equalsIgnoreCase(catalogId)){
            //增加对catalogId为0时的判断
            queryWrapper.eq("catalog_id",catalogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        //1、查出当前spuId对应的所有sku信息，以及品牌名称：
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
        //TODO 4、查询当前sku可以用来检索(searchType==0)的所有规格属性。因为多个sku可能会重复查询多次，因此，应该放在遍历之外查询：
        //1）查出当前spu对应的所有attr(商品属性)信息实体productAttrValueEntities：
        List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueService.baseAttrListForSpu(spuId);
        //2）从上面的attr信息实体productAttrValueEntities中收集attrIds：
        List<Long> attrIds = productAttrValueEntities.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        //3）从上面收集到的attrIds中筛选出可检索属性searchAttrIds：
        List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);
        //4）从所有attr信息实体productAttrValueEntities中过滤出attrId只在searchAttrIds中的部分，并封装为
        // SkuEsModel中的Attrs：
        //先将上面的searchAttrIds转换为Set，命名为searchAttrIdsSet：
        Set<Long> searchAttrIdsSet = new HashSet<>(searchAttrIds);
//        List<SkuEsModel.Attrs> attrs = new ArrayList<>();
        List<SkuEsModel.Attrs> attrsList = productAttrValueEntities.stream().filter(item -> {
            return searchAttrIdsSet.contains(item.getAttrId());
        }).map(item -> {
            //封装为SkuEsModel中的Attrs：
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs1);
            return attrs1;
        }).collect(Collectors.toList());


        //TODO 1、发送远程调用，查询库存系统是否有库存(遍历之前统一查询)：
        //对于多个sku，如果每次遍历都要远程调用库存服务进行查询，将会是一个相当缓慢的过程。
        //如果库存服务中有一个接口，能够统一查询所有sku是否有库存，则此处只需要设置是否有库存的状态即可。
        List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
//        R skuHasStock = wareFeignService.getSkuHasStock(skuIdList);
        //进行泛型化设计后，上述代码修改为(为了避免远程调用失败时影响其它后续操作，使用try/catch进行处理）：
        Map<Long, Boolean> hasStockMap = null;
        try{
            /*R<List<SkuHasStockVo>> skuHasStock = wareFeignService.getSkuHasStock(skuIdList);
            List<SkuHasStockVo> data = skuHasStock.getData();*/
            //上面代码修改为：
            R r = wareFeignService.getSkuHasStock(skuIdList);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            List<SkuHasStockVo> data = r.getData(typeReference);
            //上面的泛型化设计，好处就是，在A、B两个服务传输数据时，SpringBoot底层自动进行数据类型转换。
            hasStockMap = data.stream()
                    .collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));

        } catch (Exception e) {
            log.error("库存服务出现异常，原因：{}", e);
        }
        //上面：SkuHasStockVo::getSkuId当作map的key，item->item.getHasStock()当作map的值。

        //2、封装每一个sku的信息：
        Map<Long, Boolean> finalHasStockMap = hasStockMap;
        List<SkuEsModel> upCommodity = skus.stream().map(sku -> {
            //组装需要的数据：
            SkuEsModel skuEsModel = new SkuEsModel();
            //先做属性对拷：
            BeanUtils.copyProperties(sku,skuEsModel);
            //再处理SkuEsModel和SkuInfoEntity不一致的数据：
            //设置skuPrice、skuImg：
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            //设置hasStock、hotScore：
            //设置hasStock：
            if(finalHasStockMap==null){
                skuEsModel.setHasStock(true);
            }else {
                skuEsModel.setHasStock(finalHasStockMap.get(sku.getSkuId()));
            }

            //TODO 2、热度评分hotScore，刚上架的评分可设置为0，如果置顶，则需要指定特定值。
            //暂时简单指定为0：
            skuEsModel.setHotScore(0L);

            //TODO 3、查询品牌、分类信息：
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            //设置检索属性：
            skuEsModel.setAttrs(attrsList);

            //TODO 4、查询当前sku可以用来检索(searchType==0)的所有规格属性。因为多个sku可能会重复查询多次，因此，应该放在遍历之外查询：
            return skuEsModel;
        }).collect(Collectors.toList());

        //TODO 5、将上面收集的数据发送给bigday-search服务，然后由bigday-search服务发送给es保存：
        R r = searchFeignService.commodityStatusUp(upCommodity);
        if(r.getCode() == 0){
            //远程调用成功：
            //TODO 6、修改当前spu的状态：
            baseMapper.updateSpuStatus(spuId, CommodityConstant.StatusEnum.SPU_UP.getCode());
         }else{
            //远程调用失败：
            //TODO 7、重复调用问题（接口幂等性）：重试机制。
            //Feign调用流程：
            /**
             *  1、构造请求数据，并那个对象转换为json；
             *  如，D:/Soft-Dellvostro/Soft/Java/apache-maven-3.6.3/repository/io/github/openfeign/
             *  feign-core/10.10.1/feign-core-10.10.1-sources.jar!/
             *  feign/SynchronousMethodHandler.java中的：
             *      RequestTemplate template = buildTemplateFromArgs.create(argv);
             *  2、发送请求并执行(执行成功后，解码响应数据):
             *      return executeAndDecode(template, options);
             *  3、执行请求会有重试机制：
             *      while (true) {
             *       try {
             *         return executeAndDecode(template, options);
             *       } catch (RetryableException e) {
             *         try {
             *           retryer.continueOrPropagate(e);
             *         } catch (RetryableException th) {
             *           Throwable cause = th.getCause();
             *           if (propagationPolicy == UNWRAP && cause != null) {
             *             throw cause;
             *           } else {
             *             throw th;
             *           }
             *         }
             *         if (logLevel != Logger.Level.NONE) {
             *           logger.logRetry(metadata.configKey(), logLevel);
             *         }
             *         continue;
             *       }
             *     }
             */
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        Long spuId = byId.getSpuId();
        SpuInfoEntity spuInfoEntity = getById(spuId);
        return spuInfoEntity;
    }
}